package listbyorder.access001_100.test29;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/5/29 18:39
 */
public class Solution1 {

    // 求余数
    public int divide(int dividend, int divisor) {
        long ans = dividend((long) dividend, (long) divisor);
        long m = 2147483648L;
        if (ans == m) {
            // 此步操作的原因是因为题中假设除法结果溢出，则返回int型的最大正数
            return Integer.MAX_VALUE;
        } else {
            return (int) ans;
        }
    }

    private long dividend(long dividend, long divisor) {
        if (dividend == 0L) return 0L;
        boolean flag = true;
        if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)) {
            flag = false;
        }
        dividend = Math.abs(dividend);
        divisor = Math.abs(divisor);
        if(divisor > dividend) return 0L;
        long ans = 1;
        long pre_dividend = dividend;
        long pre_divisor = divisor;
        dividend -= divisor;  //初始化ans为1
        while (divisor <= dividend) {
            ans += ans;
            divisor += divisor;
            dividend -= divisor;
        }
        long a = ans + dividend(pre_dividend - divisor, pre_divisor);
        return flag ? a : -a;
    }
}
